/**
 * Writed by yura and mak
 */

package wz.legend.util;

import org.apache.commons.digester.Digester;
import org.apache.log4j.Logger;

import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.io.InputStream;

/**
 * User: yura
 */
public class ScriptStarterImpl implements ScriptStarter {
    private static final Logger LOG = Logger
            .getLogger(ScriptStarterImpl.class);

    private Map<String, String> scripts;

    public String getScriptName(String name) {
        if (scripts == null) {
            init();
        }
        return scripts.get(name);
    }

    private void init() {
        try {
            Digester digester = new Digester();
            digester.addObjectCreate("scripts", HashMap.class);
            digester.addCallMethod("scripts/script", "put", 2);
            digester.addCallParam("scripts/script", 0, "name");
            digester.addCallParam("scripts/script", 1);

            InputStream stream = getClass().getClassLoader()
                    .getResourceAsStream("scripts.xml");
            scripts = (Map<String, String>) digester.parse(stream);
        } catch (Exception e) {
            LOG.error(e, e);
            throw new RuntimeException(e);
        }
    }

    public String doScript(String scriptName) {
        try {
            return Utils.startProcess(getScriptName(scriptName));
        } catch (Exception e) {
            LOG.error(e, e);
        }
        return null;
    }

    public String doScript(String scriptName, String[] args) {
        StringBuffer buffer = new StringBuffer();
        for (String arg : args) {
            buffer.append(" ").append(arg);
        }
        try {
            return Utils.startProcess(getScriptName(scriptName) + buffer.toString());
        } catch (Exception e) {
            LOG.error(e, e);
        }
        return null;
    }

    public void doScriptAsync(String scriptName) {
        try {
            Utils.startProcessAsync(getScriptName(scriptName));
        } catch (Exception e) {
            LOG.error(e, e);
        }
    }

    public void doScriptAsync(String scriptName, String[] args) {
        StringBuffer buffer = new StringBuffer();
        for (String arg : args) {
            buffer.append(" ").append(arg);
        }
        try {
            Utils.startProcessAsync(getScriptName(scriptName) + buffer.toString());
        } catch (Exception e) {
            LOG.error(e, e);
        }
    }
}
